<!--suppress ALL -->
<!DOCTYPE html>
<!-- 其余原有代码 -->
<div id="formDiv"></div>
<script type="text/html" id="formContent">
  <form lay-filter="returnRecordsForm" class="layui-form model-form" id="returnRecordsForm">
    <div class="open-model">
      <div class="open-auto">
        <input name="id" type="hidden" />
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">{{d.typeNameData}}类型</label>
            <div class="layui-input-inline">
              <select id="type" name="type" lay-filter="type"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">订单类型</label>
            <div class="layui-input-inline">
              <select id="typeCode" name="typeCode" lay-filter="typeCode"></select>
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">运单编号</label>
            <div class="layui-input-inline">
              <select id="waybillNo" name="waybillNo" lay-filter="waybillNo"></select>
              <!-- <input type="hidden" name="orderId"/> -->
            </div>
          </div>
        </div>
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">关联订单编号</label>
            <div class="layui-input-inline">
              <input id="orderCode" class="layui-input" type="text" name="orderCode" disabled />
              <input type="hidden" name="orderId" />
            </div>
          </div>
        </div>
        <!-- 写一个row换行 -->
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">供应商名称</label>
            <div class="layui-input-inline">
              <input class="layui-input" disabled name="supplierName" />
              <input class="layui-input" type="hidden" name="supplierId" />
            </div>
          </div>
        </div>

        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label">{{d.typeNameData}}备注</label>
            <div class="layui-input-inline">
              <input name="remark" id="remark" class="layui-input" type="text" />
            </div>
          </div>
        </div>
        <!-- {{# if(d.eventName=="getData"||d.eventName=='setData'){ }} -->
        <div id="xxxxx">
          <div class="layui-col-md3">
            <div class="layui-form-item">
              <label class="layui-form-label">发货方式</label>
              <div class="layui-input-inline">
                <select id="returnType" name="returnType" lay-filter="returnType"></select>
              </div>
            </div>
          </div>
          <div class="layui-col-md3">
            <div class="layui-form-item">
              <label class="layui-form-label">物流公司</label>
              <div class="layui-input-inline">
                <input name="logisticsCompany" id="logisticsCompany" class="layui-input" type="text" />
              </div>
            </div>
          </div>
          <div class="layui-col-md3">
            <div class="layui-form-item">
              <label class="layui-form-label">车牌号</label>
              <div class="layui-input-inline">
                <input name="busNumber" id="busNumber" class="layui-input" type="text" />
              </div>
            </div>
          </div>
          <div class="layui-col-md3">
            <div class="layui-form-item">
              <label class="layui-form-label">物流单号</label>
              <div class="layui-input-inline">
                <input name="logisticsWaybillNo" id="logisticsWaybillNo" class="layui-input" type="text" />
              </div>
            </div>
          </div>
        </div>
        <!-- {{# } }} -->
        <div class="layui-col-md3">
          <div class="layui-form-item">
            <label class="layui-form-label w-120">物料图片</label>
            <div class="layui-input-inline">
              <div id="productPicBtn1" class="layui-btn" style="float: left;">
                <i class="layui-icon">&#xe681;</i>
                上传图片
              </div>
              <input name="fileUrl" type="hidden" class="layui-input" lay-verify="" id="fileUrl" />
              <input name="fileName" type="hidden" class="layui-input" lay-verify="" id="fileName" />
              <img id="ImgDIv" style="margin-top: 10px;width: 150px;height: 100px;display: none;" />
            </div>
          </div>
        </div>

        <div class="layui-form-item">
          <button class="layui-btn" style="margin-left: 20px" type="button" id="ConfigureItem">配置物料信息</button>
        </div>
        <table class="layui-table" lay-filter="returnRecordsFormTable" id="returnRecordsFormTable"></table>

        <div class="layui-form-item text-right">
          <div class="right-btn">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>
            <button class="layui-btn" lay-filter="productDetailSubmit" lay-submit>提交</button>
          </div>
        </div>
      </div>
    </div>
  </form>
</script>

<script>
  layui.use(['layer', 'form', 'table', 'admin', 'upload', 'tree', 'laytpl'], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    var laytpl = layui.laytpl;
    const nowData = { ...parentData };
    console.log('nowData', nowData);
    // const parentData=JSON.parse(JSON.stringify(parentData.data))
    data = nowData.data;
    // form.render('select')
    laytpl(formContent.innerHTML).render({ ...nowData }, function (html) {
      $('#formDiv').html(html);
    });
    // 表单禁用
    //    if (['detail'].includes(nowData.eventName)) {
    //        admin.setFormDisable('#returnRecordsForm', true)
    //    }
    if (['detail', 'setData', 'getData'].includes(nowData.eventName)) {
      admin.setFormDisable('#returnRecordsForm', true, '#xxxxx');
    }
    await admin.initDataSelectPro(
      'enterprisecab/warehouse/admin/warehouseInventoryType/list',
      { inventoryType: 'out', supportReturn: 1, limit: 9999, status: 'enable' },
      'typeCode',
      '订单类型',
      async (d, obj) => {
        form.val('returnRecordsForm', {
          supplierName: '',
          supplierId: '',
          orderCode: '',
          orderId: '',
        });
        table.reload('returnRecordsFormTable', {
          data: [],
        });
        $('#waybillNo').empty();
        if (d.value) {
          await admin.initDataSelectPro(
            'enterprise/sell/admin/deliveryRecord/list',
            {
              limit: 9999,
              typeCode: d.value,
            },
            'waybillNo',
            '运单编号',
            (d, obj) => {
              form.val('returnRecordsForm', {
                supplierName: '',
                supplierId: '',
                orderCode: '',
                orderId: '',
              });
              if (d.value) {
                console.log(obj);
                form.val('returnRecordsForm', {
                  supplierName: obj.customerName,
                  supplierId: obj.customerId,
                  orderCode: obj.saleOrderCode,
                  orderId: obj.saleOrderId,
                });
              }
            },
            'recordCode',
          );
        }
      },
      'name',
      'code',
    );
    await admin.initDataSelectPro('enterprise/sell/admin/customerReturnType/list', {}, 'type', `${nowData.typeNameData}类型`);
    await admin.getDictListPro('returnType', 'return_method', `发货方式`);

    table.render({
      elem: '#returnRecordsFormTable',
      data: [],
      page: true,
      cols: [
        [
          {
            tyoe: 'numbers',
            title: '序号',
            fixed: 'left',
          },
          {
            field: 'skuCode',
            title: '产品编号',
          },
          {
            field: 'skuSpec',
            title: '规格码',
          },
          {
            field: 'skuName',
            title: '产品名称',
          },
          {
            field: 'mainUnitName',
            title: '主计价单位',
          },
          {
            field: 'shipmentQty',
            title: '交付数量',
          },
          {
            field: 'mainQuantity',
            title: `${nowData.typeNameData}数量`,
            templet: admin.setTableInput('mainQuantity', ['detail', 'setData', 'getData'].includes(nowData.eventName), 'mainQuantity'),
          },
          {
            field: 'unitPrice',
            title: '单价',
            // templet: admin.setTableInput('unitPrice')
          },
          {
            field: 'totalPrice',
            title: '总价',
          },
          {
            field: 'realSendQuantity',
            title: '发货数量',
            hide: !['setData'].includes(nowData.eventName),
            templet: admin.setTableInput('realSendQuantity', false, 'mainQuantity'),
          },
          {
            field: 'realGetQuantity',
            title: '收货数量',
            hide: !['getData'].includes(nowData.eventName),
            templet: admin.setTableInput('realGetQuantity', false, 'mainQuantity'),
          },

          {
            field: 'remark',
            title: '备注',
            templet: admin.setTableInput('remark', nowData.eventName != 'add'),
          },
          // {align: 'center', toolbar: '#TableBar', title: '操作', fixed: 'right'}
        ],
      ],
      done: function (data) {
        // admin.tableInputChange('returnRecordsFormTable');
        admin.tableInputChangeByClass('returnRecordsFormTable', 'mainQuantity', (index, value, tableData, field, tableId) => {
          let totalPrice = tableData[index].unitPrice * value;
          tableData[index].totalPrice = totalPrice.toFixed(2);
          admin.setTableColHtml('returnRecordsFormTable', index, 'totalPrice', totalPrice);
        });
        admin.tableInputChangeByClass('returnRecordsFormTable', 'realSendQuantity', (index, value, tableData, field, tableId) => {
          let totalPrice = tableData[index].unitPrice * value;
          tableData[index].totalPrice = totalPrice.toFixed(2);
          admin.setTableColHtml('returnRecordsFormTable', index, 'totalPrice', totalPrice);
        });
        admin.tableInputChangeByClass('returnRecordsFormTable', 'realGetQuantity', (index, value, tableData, field, tableId) => {
          let totalPrice = tableData[index].unitPrice * value;
          tableData[index].totalPrice = totalPrice.toFixed(2);
          admin.setTableColHtml('returnRecordsFormTable', index, 'totalPrice', totalPrice);
        });
      },
    });
    if (data && data.id) {
      if (data.typeCode) {
        await admin.initDataSelectPro(
          'enterprise/sell/admin/deliveryRecord/list',
          {
            limit: 9999,
            typeCode: data.typeCode,
          },
          'waybillNo',
          '运单编号',
          null,
          'recordCode',
        );
      }
      form.val('returnRecordsForm', data);

      if (nowData.typeNameData === '退货') {
        table.reload('returnRecordsFormTable', {
          data: data.selReturnGoodsRecordsDetails,
        });
      } else {
        table.reload('returnRecordsFormTable', {
          data: data.selBarterRecordDetails,
        });
      }
    }

    $('#ConfigureItem').click(function () {
      // admin.req('enterprise/sell/admin/deliveryRecord/detail/'+$('#waybillNo').val(), {},(res)=>{
      //     console.log(res)
      // })
      const id = $('#waybillNo').val();
      if (id) {
        admin.formOpen({
          area: '1200px',
          offset: '65px',
          title: '配置物料信息',
          path: 'components/sell/returnRecords/itemTable.html',
          success: function () {
            parentData.id = id;
            parentData.list = table.cache['returnRecordsFormTable'];
          },
          end: function () {
            const newData = childData.list.map((v) => {
              v.unitPrice = v.currentCostPrice;
              return v;
            });
            let list = {
              ...table.cache['returnRecordsFormTable'],
              ...newData,
            };
            // console.log(list)
            table.reload('returnRecordsFormTable', {
              data: newData, // 设置新的数据
            });
          },
        });
      } else {
        layer.msg('请选择运单编号');
      }
      return false;
    });
    function submitFormData(url, data, method) {
      admin.req(
        url,
        JSON.stringify(data),
        function (res) {
          if (res.code == 200) {
            layer.msg('操作成功');
            table.reload('returnRecordsTable');
            layer.closeAll();
          } else {
            layer.msg(res.msg);
          }
        },
        method,
        true,
        'application/json; charset=utf-8',
      );
    }
    // 表单提交事件
    form.on('submit(productDetailSubmit)', function (d) {
      let formData = { ...d.field };
      formData.selReturnGoodsRecordsDetails = table.cache['returnRecordsFormTable'];
      formData.moduleType = nowData.typeNameData === '退货' ? 1 : 2;
      // if (nowData.typeNameData === '退货') {
      //   formData.moduleType = 1;
      // } else {
      //   formData.moduleType = 2;
      // }
      if (nowData.eventName === 'add') {
        submitFormData(nowData.addUrl, formData, 'POST');
      } else if (nowData.eventName === 'edit') {
        submitFormData(nowData.editUrl, formData, 'PUT');
      } else if (nowData.eventName === 'getData' || nowData.eventName === 'setData') {
        // getData收货  setData发货
        formData.goodType = nowData.eventName === 'getData' ? '1' : '2';
        formData.recordId = formData.id;
        formData.details = table.cache['returnRecordsFormTable'].map((v) => {
          v.recordDetailId = v.id;
          return v;
        });
        submitFormData(nowData.addLogisticsInfo, formData, 'POST');
      }
      return false;
    });
    imgUpload();
    function imgUpload() {
      upload.render({
        elem: '#productPicBtn1',
        url: config.upload_url + 'uploadFile',
        accept: 'file',
        headers: {
          Authorization: 'Bearer ' + config.getToken(),
        },
        // acceptMime: 'image/*',
        exts: 'jpg|jpeg|png|gif',
        done: function (res) {
          // On successful upload
          if (res.code === 200) {
            $('#fileUrl').val(res.data.url); // Store the image URL in hidden input
            $('#fileName').val(res.data.fileName); // Store the image URL in hidden input
            $('#ImgDIv').attr('src', res.data.url).show(); // Show image preview
            $('#ImgDIv').attr('style', 'margin-top: 10px;width: 150px;height: 100px;display: block;');
            layer.msg('图片上传成功');
          } else {
            layer.msg('图片上传失败: ' + res.msg);
          }
        },
        error: function () {
          // On upload failure
          layer.msg('上传失败，请重试');
        },
      });
    }
  });
</script>

<style>
  .layui-form-label {
    width: 100px;
  }
</style>
